package com.xd.study.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.xd.study.R;

/**
 * Created by DGF on 2015/4/28.
 */
public class PassValueFragment extends Fragment {

    /**
     * 用于Fragment向Activity传递参数
     * Activity实现该接口，Fragment中调用Activity中该接口的方法，用以传值
     */
    public interface IFragmentPassValueToActivity{
        void thank(String value);
    }

    //向Activity传递参数的接口
    private IFragmentPassValueToActivity iFragmentPassValueToActivity;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //return super.onCreateView(inflater, container, savedInstanceState);

        View view = inflater.inflate(R.layout.fragment, container, false);
        TextView textView = (TextView)view.findViewById(R.id.fragment_textview);
        Button button = (Button)view.findViewById(R.id.fragment_ok);

        //接收Activity传送的数据
        String value = getArguments().getString("name");
        textView.setText(value);
        Toast.makeText(getActivity(), "已成功接收到："+value, Toast.LENGTH_SHORT).show();

        //向Activity传递参数
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Toast.makeText(getActivity(), "向Activity发送感谢！", Toast.LENGTH_SHORT).show();

                String code = "thank you very much !";
                iFragmentPassValueToActivity.thank(code);
            }
        });

        return view;
    }

    /**
     * 获得Activity，以便调用传值接口进行传值
     * @param activity
     */
    @Override
    public void onAttach(Activity activity) {

        iFragmentPassValueToActivity = (IFragmentPassValueToActivity)activity;

        super.onAttach(activity);
    }
}
